package com.justep.baas;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.justep.baas.data.ColumnValue;
import com.justep.baas.data.Row;
import com.justep.baas.data.RowState;
import com.justep.baas.data.Table;
import com.justep.baas.data.Transform;

public class Utils {

	
	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
//	private static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss.SSS");
//	private static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
	private static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	
	public static String getLineSep() {
		return System.getProperty("line.separator");
	}
	
	public static void check(boolean isOK, Object msg1) {
		if (!isOK) {
			BaasException exp = new BaasException("" + msg1);
			throw exp;
		}
	}

	public static void check(boolean isOK, Object msg1, Object msg2) {
		if (!isOK) {
			BaasException exp = new BaasException(buildString(msg1, msg2));
			throw exp;
		}
	}

	public static void check(boolean isOK, Object msg1, Object msg2, Object msg3) {
		if (!isOK) {
			BaasException exp = new BaasException(buildString(msg1, msg2, msg3));
			throw exp;
		}
	}

	public static void check(boolean isOK, Object msg1, Object msg2, Object msg3, Object msg4) {
		if (!isOK) {
			BaasException exp = new BaasException(buildString(msg1, msg2, msg3, msg4));
			throw exp;
		}
	}

	public static void check(boolean isOK, Object msg1, Object msg2, Object msg3, Object msg4, Object msg5) {
		if (!isOK) {
			BaasException exp = new BaasException(buildString(msg1, msg2, msg3, msg4, msg5));
			throw exp;
		}
	}

	public static void check(boolean isOK, Object msg1, Object msg2, Object msg3, Object msg4, Object msg5, Object msg6) {
		if (!isOK) {
			BaasException exp = new BaasException(buildString(msg1, msg2, msg3, msg4, msg5, msg6));
			throw exp;
		}
	}

	public static void check(boolean isOK, Object msg1, Object msg2, Object msg3, Object msg4, Object msg5, Object msg6, Object msg7) {
		if (!isOK) {
			BaasException exp = new BaasException(buildString(msg1, msg2, msg3, msg4, msg5, msg6, msg7));
			throw exp;
		}
	}

	public static void check(boolean isOK, Object msg1, Object msg2, Object msg3, Object msg4, Object msg5, Object msg6, Object msg7, Object msg8) {
		if (!isOK) {
			BaasException exp = new BaasException(buildString(msg1, msg2, msg3, msg4, msg5, msg6, msg7, msg8));
			throw exp;
		}
	}

	public static void check(boolean isOK, Object msg1, Object msg2, Object msg3, Object msg4, Object msg5, Object msg6, Object msg7, Object msg8,
			Object msg9) {
		if (!isOK) {
			BaasException exp = new BaasException(buildString(msg1, msg2, msg3, msg4, msg5, msg6, msg7, msg8, msg9));
			throw exp;
		}
	}

	public static void check(boolean isOK, Object msg1, Object msg2, Object msg3, Object msg4, Object msg5, Object msg6, Object msg7, Object msg8,
			Object msg9, Object msg10) {
		if (!isOK) {
			BaasException exp = new BaasException(buildString(msg1, msg2, msg3, msg4, msg5, msg6, msg7, msg8, msg9, msg10));
			throw exp;
		}
	}

	private static String buildString(Object... objs) {
		StringBuilder sb = new StringBuilder();
		for (Object o : objs)
			sb.append(o);
		return sb.toString();
	}

	public static boolean isNotEmptyString(String obj) {
		return obj != null && obj.trim().length() != 0;
	}

	public static boolean isEmptyString(String obj) {
		return null == obj || "".equals(obj);
	}

	public static boolean isNull(Object obj) {
		return obj == null;
	}

	public static boolean isNotNull(Object obj) {
		return obj != null;
	}

    /** 
     * 获得一个UUID 
     * @return String UUID 
     */ 
    
    public static String getUUID(){ 
        String s = UUID.randomUUID().toString(); 
        //去掉“-”符号 
        return s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24); 
    } 
    
    /** 
     * 获得指定数目的UUID 
     * @param number int 需要获得的UUID数量 
     * @return String[] UUID数组 
     */ 
    
    public static String[] getUUID(int number){ 
        if(number < 1){ 
            return null; 
        } 
        String[] ss = new String[number]; 
        for(int i=0;i<number;i++){ 
            ss[i] = getUUID(); 
        } 
        return ss; 
    } 

    
    
    
    
    
    ///////////////////////我自己添加的/////////////////////////////////////////////
    
    
 	/*
 	public static String getCurrentDate() throws ParseException{
 		Calendar now = Calendar.getInstance();  
         System.out.println("年: " + now.get(Calendar.YEAR));  
         System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");  
         System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));  
         System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));  
         System.out.println("分: " + now.get(Calendar.MINUTE));  
         System.out.println("秒: " + now.get(Calendar.SECOND));  
         System.out.println("当前时间毫秒数：" + now.getTimeInMillis());  
         System.out.println(now.getTime());  
   
         Date d = new Date();  
         System.out.println(d);  
//         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
         String dateNowStr = DATE_FORMAT.format(d);  
         System.out.println("格式化后的日期：" + dateNowStr);  

         return dateNowStr;
 	}
 	*/
 	
 	public static java.sql.Date getCurrentDate(){
// 		Calendar now = Calendar.getInstance();  
//         System.out.println("年: " + now.get(Calendar.YEAR));  
//         System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");  
//         System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));  
//         System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));  
//         System.out.println("分: " + now.get(Calendar.MINUTE));  
//         System.out.println("秒: " + now.get(Calendar.SECOND));  
//         System.out.println("当前时间毫秒数：" + now.getTimeInMillis());  
//         System.out.println(now.getTime());  
   
         Date d = new Date();  
//         System.out.println(d);  
//         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
         String dateNowStr = DATE_FORMAT.format(d);  
//         System.out.println("格式化后的日期：" + dateNowStr);  
         java.sql.Date currentDate = java.sql.Date.valueOf(dateNowStr);
         return currentDate;
 	}
 	
 	public static java.sql.Date getCurrentDate(java.util.Date d){
//         System.out.println(d);  
//         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
         String dateNowStr = DATE_FORMAT.format(d);  
//         System.out.println("格式化后的日期：" + dateNowStr);  
         java.sql.Date currentDate = java.sql.Date.valueOf(dateNowStr);
         return currentDate;
 	}

 	
 	/*
 	public static String getCurrentDateTime() throws ParseException{
 		Calendar now = Calendar.getInstance();  
         System.out.println("年: " + now.get(Calendar.YEAR));  
         System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");  
         System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));  
         System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));  
         System.out.println("分: " + now.get(Calendar.MINUTE));  
         System.out.println("秒: " + now.get(Calendar.SECOND));  
         System.out.println("当前时间毫秒数：" + now.getTimeInMillis());  
         System.out.println(now.getTime());  
   
         Date d = new Date();  
         System.out.println(d);  
//         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
         String dateNowStr = DATETIME_FORMAT.format(d);  
         System.out.println("格式化后的日期时间：" + dateNowStr);  
           
//         String str = "2012-1-13 17:26:33";  //要跟上面sdf定义的格式一样  
//         Date today = sdf.parse(str);  
//         System.out.println("字符串转成日期：" + today);
         
         return dateNowStr;
 	}
 	*/
 	
 	public static Timestamp getCurrentDateTime(){
// 		new Timestamp(System.currentTimeMillis());
// 		Calendar now = Calendar.getInstance();  
//         System.out.println("年: " + now.get(Calendar.YEAR));  
//         System.out.println("月: " + (now.get(Calendar.MONTH) + 1) + "");  
//         System.out.println("日: " + now.get(Calendar.DAY_OF_MONTH));  
//         System.out.println("时: " + now.get(Calendar.HOUR_OF_DAY));  
//         System.out.println("分: " + now.get(Calendar.MINUTE));  
//         System.out.println("秒: " + now.get(Calendar.SECOND));  
//         System.out.println("当前时间毫秒数：" + now.getTimeInMillis());  
//         System.out.println(now.getTime());  
   
         Date d = new Date();  
//         System.out.println(d);  
//         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
         String dateNowStr = DATETIME_FORMAT.format(d);  
//         System.out.println("格式化后的日期时间：" + dateNowStr);  
           
//         String str = "2012-1-13 17:26:33";  //要跟上面sdf定义的格式一样  
//         Date today = sdf.parse(str);  
//         System.out.println("字符串转成日期：" + today);
         
         Timestamp currentDateTime = Timestamp.valueOf(dateNowStr);
 		
        return currentDateTime;
 	}
 	
 	public static long getCurrentTimeMillis(){
 		return System.currentTimeMillis();
 	}

 	//获取星期
 	public static String getWeekOfDate(Date dDate){
 		String[] weekDays = {"日", "一", "二", "三", "四", "五", "六"};//{"<日>", "<一>", "<二>", "<三>", "<四>", "<五>", "<六>"};//{"SUN","MON","TUE","WED","THU","FRI","SAT"};//{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
         Calendar cal = Calendar.getInstance();
         cal.setTime(dDate);
         int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
         if (w < 0)
             w = 0;
         return weekDays[w];
 	}
 	
 	public static java.sql.Date toDate(String dateStr){
  
         Date d = java.sql.Date.valueOf(dateStr); 
         System.out.println(d);  
//         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
         String dateNowStr = DATE_FORMAT.format(d);  
         System.out.println("格式化后的日期：" + dateNowStr);  
         java.sql.Date currentDate = java.sql.Date.valueOf(dateNowStr);
         return currentDate;
 	}
 	
 	/**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        //例如比较当前时间和早上6：00
        String nowTime = new SimpleDateFormat("HH:MM").format(new Date());
        System.out.println("当前时间为："+nowTime);
        System.out.println("与当日06：00相比");
        int i = DateCompare(nowTime,"06:00","HH:MM");
        switch (i) {
        case 0:
            System.out.println("两个时间相等");
            break;
        case 1:
            System.out.println("当前时间晚于06:00");
            break;
        case -1:
            System.out.println("当前时间早于06:00");
            break;
        default:
            break;
        }
         
    }
 	/**
     * 根据时间类型比较时间大小 
     * 
     * @param source
     * @param traget
     * @param type "YYYY-MM-DD" "yyyyMMdd HH:mm:ss"  类型可自定义
     * @param 传递时间的对比格式
     * @return 
     *  0 ：source和traget时间相同    
     *  1 ：source比traget时间大  
     *  -1：source比traget时间小
     * @throws Exception
     */
    public static int DateCompare(String source, String traget, String type) throws Exception {
        int ret = 2;
        SimpleDateFormat format = new SimpleDateFormat(type);
        Date sourcedate = format.parse(source);
        Date tragetdate = format.parse(traget);
        ret = sourcedate.compareTo(tragetdate);
        return ret;
    }	
 	
 	/**
 	 * 将一个数组连接为格式化字符串
 	 * @param objects
 	 * @param format 对数组元素的格式化，例如：'%s'为每个数组元素增加单引号、(%s = ?)将每个数组元素格式化为括号中等于问号
 	 * @param separator 分隔符，例如：,、OR、AND
 	 * @return
 	 */
 	/*
 	public static String arrayJoin(Object[] objects, String format, String separator) {
 		StringBuffer buf = new StringBuffer();
 		for (Object o : objects) {
 			if (buf.length() > 0) {
 				buf.append(separator);
 			}
 			buf.append(String.format(format, o.toString()));
 		}
 		return buf.toString();
 	}
 	*/

 	/**
 	 * 判断是否空字符串
 	 * @param s
 	 * @return
 	 */
 	/*
 	public static boolean isEmptyString(String s) {
 		return s == null || s.trim().length() == 0;
 	}
 	*/
    
    
	public static String getDefCols(Class<?> c){
	    System.out.println("类名:"+c.getName());
		//初始化列集
//		Map<String, DataType> columns = new LinkedHashMap<String, DataType>();
	      
	    Field[] fields = c.getDeclaredFields();
	    
	    String defCol = "";
	    for(int i =0;i<fields.length;i++){
	    	if(i==0){
	    		defCol = defCol+"{";
	    	}
	    	
//	    	System.out.println(fields[i].getName());
	    	//排除rowState和serialVersionUID特殊列
	    	if("rowState".equals(fields[i].getName()) || "serialVersionUID".equals(fields[i].getName())){
	    		continue;
	    	}
	    	
	    	String columnType = fields[i].getType().toString().substring(fields[i].getType().toString().lastIndexOf(".")+1);
	    	//单独处理int/BigDecimal/Timestamp类型
	    	if(columnType.equals("int")){
	    		columnType = "Integer";
	    	}
	    	if(columnType.equals("BigDecimal")){
	    		columnType = "Decimal";
	    	}
	    	if(columnType.equals("Timestamp")){
	    		columnType = "Datetime";
	    	}

//	    	System.out.println(fields[i].getType().toString());
    		defCol = defCol+fields[i].getName()+":{"
	    	+"name:\""+fields[i].getName()+"\","
	    	+"type:\""+columnType+"\","
	    	+"label:\"\"}"
	    	;
	    	/*
	    	if(fields[i].getType().toString().indexOf("class")!= -1){
	    		//表示是java的数据类型，否则表示为用户自定义类型
	        	String str = fields[i].getType().toString().substring(fields[i].getType().toString().lastIndexOf(".")+1);
	        	System.out.println("str----------------->"+str);
	        	columns.put(fields[i].getName(), DataType.parse(str));
	    	}
	    	*/
	    	if(i==fields.length - 2){
	    		defCol = defCol+"}";
	    	}else{
	    		defCol = defCol+",";
	    	}
	    	
	    }
	    return defCol;
	}
    
 	//这个可不是测试用的，用于产生前端需要的defCol格式数据
 	public static JSONObject entityToDefColJSON(Class<?> c){
 	    String defCol = getDefCols(c);
 	    return JSONObject.parseObject(defCol);
 	}



	public static String orgID2FullID(String orgID) {
		String orgFullID = "/" + orgID +".ogn";
		return orgFullID;
	}

	public static String orgFullID2ID(String orgFullID) {
		System.out.println("orgFullID-->>"+orgFullID);
		String orgID = orgFullID.replace("/", "");
		System.out.println("orgID-->>"+orgID);
		String[] strs = orgID.split("\\.");
		orgID = strs[0];
		System.out.println("orgID-->>"+orgID);
		return orgID;
	}
	
	public static JSONObject newData(JSONObject data) {
		//缺省列
		String defColstr = data.getString("defColstr");
		JSONObject defCols = JSONObject.parseObject(defColstr);

		//表名
		String concept = data.getString("concept");
		//ID列
		String idColumnDefine = data.getString("idColumnDefine");
		
		//缺省值
		JSONArray defaultValues = data.getJSONArray("defaultValues");
		//System.out.println("defaultValues-->>"+defaultValues);

		//循环列
//		for(String name: defCols.keySet()) {
//			System.out.println(name+":"+defCols.getJSONObject(name).getString("type"));
//		}
		//创建表
		Table table = Transform.createTableByColumnsDefine(defCols);
		table.setIDColumn(idColumnDefine);
		int offset = data.getIntValue("offset");
		table.setOffset(offset);
		table.setTableName(concept);
		table.setTotal(defaultValues.size());
		
		String[] ids = new String[defaultValues.size()];
		Map<String, ColumnValue> values = new HashMap<String, ColumnValue>();
		//循环缺省值（多行）
		for(int i=0;i<defaultValues.size();i++) {
			JSONObject rowValue = defaultValues.getJSONObject(i);
			//循环列
			for(String name: table.getColumnNames()) {
				//System.out.println(name+":"+table.getColumnType(name));
				//循环缺省值（单行）
				for(String col: rowValue.keySet()) {
					//System.out.println(col+":"+rowValue.get(col));
					if(col.equals(name)) {
						Object value = rowValue.get(col); 
						Object oldValue = rowValue.get(col); 
						boolean changed = false;
						ColumnValue colvalue = new ColumnValue(value, oldValue, changed);
						values.put(name, colvalue);
					}
				}
			}
			
			String id = Utils.getUUID();
			ids[i] = id;
			//设置ID列
			Object value = id; 
			Object oldValue = value; 
			boolean changed = false;
			ColumnValue colvalue = new ColumnValue(value, oldValue, changed);
			values.put(table.getIDColumn(), colvalue);
			
			Object valueVerson = 0; 
			Object oldValueVerson = value; 
			boolean changedVerson = false;
			ColumnValue colvalueVerson = new ColumnValue(valueVerson, oldValueVerson, changedVerson);
			values.put("version", colvalueVerson);
			
			RowState state = RowState.NEW;
			Row row = new Row(values, state);
			table.appendRow(row);

		}
		
		JSONObject jsondata = Transform.tableToJson(table);
		data.put("ids", ids);

		JSONObject json = new JSONObject();
		json.put("code", 0);
		json.put("msg", "success");
		json.put("data", jsondata);
		
		return json;
	}
	
	
 	
}
